import type {
  requestInterceptorType,
  requestInterceptorCatchType,
  responseInterceptorType,
  responseInterceptorCatchType,
  InterceptorsType,
  RequestTransform
  // RequestMethodConfig
} from '../axios-request'

import { isAxiosError, isCancelError } from '../axios-request'
import { checkStatus } from './check-status'

import { ResultEnum, showErrorMessage } from './helper'

import { Toast } from 'vant'

import { useAppStore } from '@/store'

const requestInterceptorImpl: requestInterceptorType = (config) => {
  useAppStore().isLoading = true
  return config
}

const requestInterceptorCatchImpl: requestInterceptorCatchType = (error) => {
  useAppStore().isLoading = false
  return Promise.reject(error)
}

const responseInterceptorImpl: responseInterceptorType = (response) => {
  useAppStore().isLoading = false
  return response
}

const responseInterceptorCatchImpl: responseInterceptorCatchType = async (
  error
) => {
  useAppStore().isLoading = false
  if (isCancelError(error)) return Promise.reject(error)
  return Promise.reject(error)
}

const clearToastMsg = () => {
  Toast.clear()
}

export const transformResponse: RequestTransform['transformResponse'] = (
  response,
  requestConfigEx
) => {
  const { ignoreResponseErrorMessage = false } = requestConfigEx

  const { data: _data } = response
  const { code, message = '' } = _data || {}

  switch (code) {
    case ResultEnum.SUCCESS:
      return _data

    default: {
      // 根据具体业务来确定默认值
      const errorJson = {
        message: message || '服务器错误',
        code: code || -1,
        data: null
      }

      !ignoreResponseErrorMessage && showErrorMessage(errorJson.message)

      console.error(
        '[AxiosRequest error]:',
        `${response?.config?.method?.toUpperCase()} ${
          response?.request?.responseURL
        } ${errorJson.code} (${errorJson.message})`
      )

      throw errorJson
    }
  }
}

export const requestCatch: RequestTransform['requestCatch'] = (
  error,
  requestOptionsEx
) => {
  const { ignoreErrorMessage = false } = requestOptionsEx

  if (isCancelError(error)) return error

  if (!isAxiosError(error)) {
    !ignoreErrorMessage &&
      !isCancelError(error) &&
      showErrorMessage(error.message)

    return error
  }

  checkStatus(Number(error.response?.status))

  return error
}

export const interceptorHooks: InterceptorsType = {
  requestInterceptor: requestInterceptorImpl,
  requestInterceptorCatch: requestInterceptorCatchImpl,
  responseInterceptor: responseInterceptorImpl,
  responseInterceptorCatch: responseInterceptorCatchImpl
}
